package com.qf.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qf.constant.JxcConstant;
import com.qf.dto.UserDTO;
import com.qf.service.UserService;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(allowCredentials = "true")
public class UserController {

    @Reference
    private UserService userService;

    // 用户登录功能
    @PostMapping("/login")
    public ResultVO login(String username, String password, HttpSession session){
        //1. 校验请求参数是否合法.
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            // 用户名或密码为空..
            log.info("【用户登录】 参数不合法  ,   username = {},password = {}",username,password);
            // 错误时返回的信息
            return new ResultVO(138,"参数不合法!!",null);
        }
        //2. 调用service执行登录的业务. DTO -> Data Transport Object
        UserDTO userDTO = userService.login(username,password);
        // 用户登录成功
        session.setAttribute(JxcConstant.SESSION_USER,userDTO);

        //3. 响应成功信息.
        return new ResultVO(0,"成功",null);
    }

    // 获取用户真实姓名(从session中获取)
    @GetMapping("/info")
    public ResultVO info(HttpSession session){
        //1. 从session中获取用户信息.
        UserDTO user = (UserDTO) session.getAttribute(JxcConstant.SESSION_USER);
        //2. 为null,用户未登录.
        if(user == null){
            log.info("【获取用户真实姓名】 当前用户未登录!!!");
            return new ResultVO(123,"用户未登录!!",null);
        }
        //3. 不为null,响应正确数据
        return new ResultVO(0,"成功",user.getRealname());
    }


}
